
// import { SysMenuService } from '../menu/menu.service';
import { Body, Controller, Post,Get, Req } from '@nestjs/common';
import {
  ApiOkResponse,
  ApiOperation,
  ApiSecurity,
  ApiTags,
} from '@nestjs/swagger';
import { ADMIN_PREFIX } from '../../admin.constants';
import { SysRoleService } from './role.service';
import { IpcErrorException } from '@main/common/exceptions/ipc.exception'
import { AdminUser } from '../../core/decorators/admin-user.decorator';
import { FastifyRequest } from 'fastify';

@ApiSecurity(ADMIN_PREFIX)
@ApiTags('角色模块')
@Controller('role')
export class SysRoleController {
  constructor(
    private roleService: SysRoleService,
    // private menuService: SysMenuService,
  ) { }

  // 获取角色列表
  @ApiOperation({ summary: '获取角色列表' })
  @ApiOkResponse()
  @Get('list')
  async list() {
    return await this.roleService.list();
  }

  // 分页查询角色信息
  @ApiOperation({ summary: '分页获取获取角色列表' })
  @ApiOkResponse()
  @Post('page')
  async page(@Body() dto) {
    const [list, total] = await this.roleService.page(dto);

    return {
      list,
      pagination: {
        total,
        pageNum: dto.pageNum,
        pageSize: dto.pageSize,
      },
    };
  }

  // 新增角色
  @ApiOperation({ summary: '添加角色' })
  @ApiOkResponse()
  @Post('add')
  async add(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;
    
    await this.roleService.isExistKey(dto.name)

    const res = await this.roleService.add(dto, user, mac, ip, syncHostSqlite);

    return res;
  }

  // 更新角色
  @ApiOperation({ summary: '更新角色' })
  @ApiOkResponse()
  @Post('update')
  async update(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;
    await this.roleService.update(dto, user, mac, ip, syncHostSqlite);
  }

  // 删除角色
  @ApiOperation({ summary: '删除角色' })
  @ApiOkResponse()
  @Post('delete')
  async delete(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;
    const count = await this.roleService.countUserIdByRole(dto);

    if (count > 0) {
      return IpcErrorException('数据被引用')
    }

    await this.roleService.delete(dto, user, mac, ip, syncHostSqlite);
  }


  @ApiOperation({ summary: '获取用户信息' })
  @ApiOkResponse()
  @Post('info')
  async info(@Body() dto) {
    return await this.roleService.info(dto.id);
  }
}
